package com.alibaba.fastjson.serializer;

import com.github.littleantfly.dictionary.utils.DictUtil;
import com.github.littleantfly.dictionary.annotation.Dict;
import com.github.littleantfly.dictionary.config.DictProperties;
import com.github.littleantfly.dictionary.module.DictModel;
import com.github.littleantfly.dictionary.service.DictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * Fastjson 字典数据注入
 *
 * @author xiezhenglong
 */
public class DictFieldSerializerFilter extends AfterFilter {

    private final Logger logger = LoggerFactory.getLogger(DictFieldSerializerFilter.class);

    private final DictService dictService;

    private final DictProperties dictProperties;

    public DictFieldSerializerFilter(DictService dictService, DictProperties dictProperties) {
        this.dictService = dictService;
        this.dictProperties = dictProperties;
    }

    @Override
    public void writeAfter(Object object) {
        try {
            Field[] declaredFields = object.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                try {
                    field.setAccessible(true);
                    Dict annotation = field.getAnnotation(Dict.class);
                    if (annotation == null) {
                        continue;
                    }
                    String fieldName = field.getName();
                    String cacheKey = DictUtil.getKey(annotation, fieldName);
                    DictUtil.getDict(dictService, cacheKey, field.get(object)).ifPresent(d->{
                        super.writeKeyValue(fieldName + dictProperties.getSuffix(), d);
                    });
                } catch (Exception e) {
                    logger.error("filedName = {} write dict data error, error={}", field.getName(), e.getMessage());
                }
            }
        } catch (Exception e) {
            logger.error("write dict data error, {}", e.getMessage());
        }
    }


}
